<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .input-wrap {
      width: 240px;
      height: 32px;
      border: 1px solid;
      border-radius: 2px;
    }
    input {
      border: 0;
      width: 200px;
      height: 30px;
      outline: none;
    }
  </style>
</head>
<body>
  <div id="app">
    <h2>缓存组件</h2>
    <button @click="componentName = 'Tab1'">111</button>
    <button @click="componentName = 'Tab2'">222</button>
    <button @click="componentName = 'Tab3'">333</button>
    <button @click="componentName = 'Tab4'">444</button>

    <!-- keep-alive标签是一个缓存组件标签 -->
    <!-- 加了keep-alive之后，被切走的组件就不会被销毁了，重新进来的时候就不会重新创建了 -->
    <!-- 比如数据请求不需要重新发送了，页面的操作的状态就可以保留了 -->
    <keep-alive>
      <component :is="componentName"></component>
    </keep-alive>
    
  </div>

  <script src="../vue3.js"></script>
  <script>
    const {createApp} = Vue;

    const Tab1 = {
      template: `
        <div>这是tab1组件</div>
      `,
      mounted() {
        console.log("tab1加载完成");
      },
      beforeUnmount() {
        console.log("tab1销毁了");
      }
    }
    let timer;
    const Tab2 = {
      data() {
        return {
          count: 1
        }
      },
      template: `
        <div>这是tab2组件</div>
        <p>count: {{ count }}</p>
        <button @click="count++">count++</button>
      `,
      mounted() {
        console.log("tab2加载完成");
      },
      beforeUnmount() {
        console.log("tab2销毁了");
        // clearInterval(timer);
      },

      // 特殊的生命周期
      activated() {
        // 若组件实例是 <KeepAlive> 缓存树的一部分，当组件被插入到 DOM 中时调用。
        console.log("tab2 activated");
        timer = setInterval(() => {
          this.count++;
        }, 1000)
      },
      deactivated() {
        // 若组件实例是 <KeepAlive> 缓存树的一部分，当组件从 DOM 中被移除时调用。
        console.log("tab2 deactivated");
        clearInterval(timer);
      }
    }
    const Tab3 = {
      template: `
        <div>这是tab3组件</div>
      `,
      mounted() {
        console.log("tab3加载完成");
      },
      beforeUnmount() {
        console.log("tab3销毁了");
      }
    }
    const Tab4 = {
      template: `
        <div>这是tab4组件</div>
      `
    }

    const app = createApp({
      data() {
        return {
          componentName: "Tab1"
        }
      },
      components: {
        Tab1,
        Tab2,
        Tab3,
        Tab4
      }
    });

    app.mount("#app");
  </script>
</body>
</html>